package com.pro01.backend.mapper;

import com.pro01.backend.pojo.Notification;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface NotificationMapper {

    // 插入通知
    @Insert("""
        INSERT INTO notifications (user_id, type, sender_id, content, link, status, created_at)
        VALUES (#{userId}, #{type}, #{senderId}, #{content}, #{link}, #{status}, NOW())
    """)
    int insertNotification(Notification notification);

    // 查询通知列表
    @Select("""
    SELECT *
    FROM notifications
    WHERE user_id = #{userId}
    ORDER BY created_at DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<Notification> selectNotifications(@Param("userId") Long userId,
                                           @Param("offset") int offset,
                                           @Param("pageSize") int pageSize);

    @Select("""
    SELECT COUNT(*)
    FROM notifications
    WHERE user_id = #{userId}
""")
    int countNotifications(@Param("userId") Long userId);

    // 查询未读通知数量
    @Select("""
    SELECT COUNT(*)
    FROM notifications
    WHERE user_id = #{userId}
      AND status = 'UNREAD'
""")
    int countUnreadNotifications(@Param("userId") Long userId);

    // 把通知标记已读
    @Update("""
    UPDATE notifications
    SET status = 'READ'
    WHERE id = #{notificationId}
      AND user_id = #{userId}
      AND status = 'UNREAD'
""")
    int markNotificationAsRead(@Param("notificationId") Long notificationId,
                               @Param("userId") Long userId);

    // 批量标记通知为已读
    @Update("""
    UPDATE notifications
    SET status = 'READ'
    WHERE user_id = #{userId}
      AND status = 'UNREAD'
""")
    int markAllNotificationsAsRead(@Param("userId") Long userId);

    // 管理员查看自己发布的所有系统通知
    @Select("""
    SELECT 
        MIN(id) AS id, 
        NULL AS user_id, 
        'SYSTEM_NOTICE' AS type, 
        NULL AS sender_id,
        content,
        link,
        NULL AS status,
        MIN(created_at) AS created_at
    FROM notifications
    WHERE type = 'SYSTEM_NOTICE'
    GROUP BY content, link
    ORDER BY created_at DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<Notification> selectGroupedSystemNotifications(@Param("offset") int offset,
                                                        @Param("pageSize") int pageSize);

    @Select("""
    SELECT COUNT(DISTINCT content, link)
    FROM notifications
    WHERE type = 'SYSTEM_NOTICE'
""")
    int countGroupedSystemNotifications();

    // 删除系统通知
    @Delete("""
    DELETE FROM notifications
    WHERE type = 'SYSTEM_NOTICE'
      AND content = #{content}
      AND (link = #{link} OR (link IS NULL AND #{link} IS NULL))
""")
    int deleteSystemNotification(@Param("content") String content,
                                 @Param("link") String link);

}
